package org.huangrui.algorithm;

/**
 * @Author hr
 * @Create 2025-11-03 13:31
 * 27. 移除元素
 * https://leetcode.cn/problems/remove-element/
 * 快慢相等值不变，慢针不动快针走；
 * 快慢不等值，我是题型2，快针慢针值互换，慢针向前一步走，快针向前一步走；
 **/
public class T022LeetCode027 {
    public int removeElement(int[] nums, int val) {
        int fast = 0, slow = 0;
        //nums = [0,1,2,2,3,0,4,2], val = 2
        //给 nums[slow] 赋值然后再给 slow++，这样可以保证 nums[0..slow-1]是不包含值为 val 的元素的，
        // 最后的返回的slow指针槽位，刚好就是数组长度就是nums.length=5，注意数组长度为5，数组下标index从0-4
        // 指针槽位号 = 数组长度length = 数组下标从0至length-1
        while (fast < nums.length) {
            if (nums[fast] != val) {
                nums[slow] = nums[fast];
                slow++;
            }
            fast++;
        }
        //下标从零开始，slow指针槽位号刚好就是数组长度
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i]+" ");
        }
        System.out.println();
        for (int i = 0; i < slow; i++) {
            System.out.print(nums[i]+" ");
        }
        return slow;
    }

    public static void main(String[] args) {
        T022LeetCode027 leetCode = new T022LeetCode027();
        // int[] ints = {3,2,2,3};
        // int val = 3;

        int[] ints = {0, 1, 2, 2, 3, 0, 4, 2};
        int val = 2;
        leetCode.removeElement(ints, val);
    }
}
